#include "../lvgl/lvgl.h"
#include "iu_manage.h"
#include <string.h>
#include <stdio.h>
#include <time.h>

#define MAX_IMAGES 50
#define MAX_PATH_LENGTH 256

// // 图像路径数组
// static const char * img_path[] = {"S:/afanda.png", "S:/jiulongchengzhai.png", "S:/tiaochubaieji.png", "S:/tiaozhan.png",
//  "S:/wanliguitu.png"};
// 图像路径数组
static char* img_path[MAX_IMAGES];
static uint32_t img_count = 0;
static uint32_t img_index = 0;        // 当前图片索引

static lv_obj_t * img = NULL;              // 图片对象（全局，供定时器访问）
static lv_obj_t * slideshow_screen = NULL; // 幻灯片屏幕对象
static lv_timer_t * slide_timer    = NULL; // 幻灯片定时器
// static lv_timer_t * time_timer     = NULL; // 时间更新定时器 - 删除这一行
static lv_obj_t * label_time = NULL;
static lv_obj_t *btn1 = NULL, *btn2 = NULL, *btn3 = NULL; // 按钮对象

// 添加一个标志来跟踪slideshow_screen是否被隐藏
static bool slideshow_screen_hidden = false;


// 函数声明
static void load_images_from_directory(void);
static lv_obj_t * create_button(lv_obj_t * parent, const char * text, lv_coord_t x, lv_coord_t y, lv_coord_t w,
                                lv_coord_t h, lv_event_cb_t event_cb);
static void cleanup_slideshow_screen(void);

// 加载目录中的图片
static void load_images_from_directory(void) {
    // 先释放已有的图片路径内存
    for (uint32_t i = 0; i < img_count; i++) {
        if (img_path[i]) {
            free(img_path[i]);
            img_path[i] = NULL;
        }
    }
    img_count = 0;
    
    // 确保目录存在
    system("mkdir -p /nfs/39-lvgl/lv_port_linux_frame_buffer-release-v8.2/images/png");
    
    // 使用项目根目录下的images/png目录
    const char* image_dir = "/nfs/39-lvgl/lv_port_linux_frame_buffer-release-v8.2/images/png";
    const char* list_file = "/nfs/39-lvgl/lv_port_linux_frame_buffer-release-v8.2/images/png/png.txt";
    
    // 构建命令获取图片列表
    char cmd[256];
    snprintf(cmd, sizeof(cmd), "ls %s/*.png > %s 2>/dev/null", image_dir, list_file);
    
    LV_LOG_USER("执行命令: %s", cmd);
    
    // 执行系统命令获取图片列表
    int result = system(cmd);
    if (result != 0) {
        LV_LOG_USER("执行命令失败，返回码: %d", result);
    }
    
    FILE * fp = fopen(list_file, "r");
    if (!fp) {
        LV_LOG_USER("无法加载图片列表，使用默认图片路径。");
        // 如果无法打开文件，使用默认图片路径（使用S:前缀格式）
        static const char * default_img_path[] = {
            "S:/png/afanda.png", 
            "S:/png/jiulongchengzhai.png", 
            "S:/png/tiaochubaieji.png", 
            "S:/png/tiaozhan.png",
            "S:/png/wanliguitu.png", 
        };
        
        int default_count = sizeof(default_img_path) / sizeof(default_img_path[0]);
        for (int i = 0; i < default_count && img_count < MAX_IMAGES; i++) {
            LV_LOG_USER("添加默认图片: %s", default_img_path[i]);
            img_path[img_count] = strdup(default_img_path[i]);
            img_count++;
        }
        return;
    }
    
    LV_LOG_USER("成功加载图片列表文件");
    char line[MAX_PATH_LENGTH];
    while (fgets(line, sizeof(line), fp) && img_count < MAX_IMAGES) {
        // 移除换行符
        line[strcspn(line, "\n")] = 0;
        if (strlen(line) > 0) {
            // 将实际路径转换为S:前缀格式
            // 例如: /nfs/39-lvgl/lv_port_linux_frame_buffer-release-v8.2/images/png/afanda.png
            // 转换为: S:/png/afanda.png
            char *filename = strrchr(line, '/');
            if (filename) {
                filename++; // 跳过 '/'
                static char s_path[256];
                snprintf(s_path, sizeof(s_path), "S:/png/%s", filename);
                LV_LOG_USER("转换路径: %s -> %s", line, s_path);
                img_path[img_count] = strdup(s_path);
                img_count++;
            } else {
                // 如果无法解析文件名，使用原始路径
                LV_LOG_USER("加载图片路径: %s", line);
                img_path[img_count] = strdup(line);
                img_count++;
            }
        }
    }
    
    fclose(fp);
    // 删除临时文件
    remove(list_file);
}

// 清理函数
static void cleanup_slideshow_screen(void) {
    // 停止并删除所有定时器
    if(slide_timer) {
        lv_timer_del(slide_timer);
        slide_timer = NULL;
    }
    if(time_timer) {
        lv_timer_del(time_timer);
        time_timer = NULL;
    }
    // 释放图片路径内存
    cleanup_images();
    // 重置所有对象指针
    img = NULL;
    label_time = NULL;
    btn1 = btn2 = btn3 = NULL;
    slideshow_screen = NULL;
}
// 图片自适应函数
void set_image_adaptive(lv_obj_t * img_obj, const char * src, lv_coord_t max_w, lv_coord_t max_h)
{
    // 检查参数
    if(!img_obj || !src) return;

    // 获取图片信息
    lv_img_header_t header;
    lv_res_t result = lv_img_decoder_get_info(src, &header);

    if(result == LV_RES_OK) {
        uint32_t orig_w = header.w;
        uint32_t orig_h = header.h;

        if(orig_w > 0 && orig_h > 0) {
            // 计算缩放比例
            float scale_x = (float)max_w / orig_w;
            float scale_y = (float)max_h / orig_h;
            float scale   = (scale_x < scale_y) ? scale_x : scale_y;

            // 确保不会放大图片
            if(scale > 1.0f) scale = 1.0f;

            // 计算新尺寸
            lv_coord_t new_w = (lv_coord_t)(orig_w * scale);
            lv_coord_t new_h = (lv_coord_t)(orig_h * scale);

            // 设置图片尺寸
            lv_obj_set_size(img_obj, new_w, new_h);
        }
    } else {
        // 如果无法获取图片信息，设置默认尺寸
        lv_obj_set_size(img_obj, 200, 150);
    }

    // 设置图片源
    lv_img_set_src(img_obj, src);
}

// 定时器回调函数：切换图片
void img_switch_timer(lv_timer_t * timer)
{
    // 安全检查
    if(!timer || !img || !slideshow_screen) return;

    // 切换到下一张图片（循环）
    if (img_count > 0) {
        img_index = ((img_index + 1) % img_count);
        
        // 更新图片源并添加淡入淡出效果
        lv_obj_set_style_img_opa(img, LV_OPA_0, 0);
        lv_img_set_src(img, img_path[img_index]);

        // 创建淡入动画
        lv_anim_t anim;
        lv_anim_init(&anim);
        lv_anim_set_var(&anim, img);
        lv_anim_set_values(&anim, LV_OPA_0, LV_OPA_100);
        lv_anim_set_time(&anim, 500);
        lv_anim_set_exec_cb(&anim, (lv_anim_exec_xcb_t)lv_obj_set_style_img_opa);
        lv_anim_start(&anim);
    }
}

// 更新时间显示
void update_time_timer(lv_timer_t * e)
{
    // 安全检查
    if(!e || !label_time || !slideshow_screen) return;

    // 获取当前系统时间
    time_t now;
    struct tm * t;
    time(&now);
    t = localtime(&now);
    if(!t) return;

    char time_str[64];
    // 星期几转换
    const char * weather[] = {"阴", "晴", "多云", "小雨", "暴雨", "雷阵雨", "暴风雨"};
    const char * weekday[] = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    snprintf(time_str, sizeof(time_str), "%s   %s   %d年%d月%d日   %02d:%02d:%02d", weather[t->tm_wday],
             weekday[t->tm_wday], t->tm_year + 1900,
             t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
    lv_label_set_text(label_time, time_str);
}

// 安全事件处理模板
static void safe_event_handler(lv_event_t* e) {
    if(!e) {
        LV_LOG_ERROR("Null event pointer");
        return;
    }
    
    lv_obj_t* target = lv_event_get_target(e);
    if(!target) {
        LV_LOG_ERROR("Null event target");
        return;
    }
}


void button1_click_handler(lv_event_t * e)
{
    safe_event_handler(e);
    if(!e) return;

    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        LV_LOG_USER("Handling ticket pickup click");
        // 停止定时器
        if(slide_timer) {
            lv_timer_pause(slide_timer);
        }
        // 隐藏当前界面
        if(slideshow_screen) {
            lv_obj_add_flag(slideshow_screen, LV_OBJ_FLAG_HIDDEN);
            slideshow_screen_hidden = true;
        }
        // 跳转到取票页面
        pick_up_screen_init();
    }
    // 添加按钮按下效果
    else if(code == LV_EVENT_PRESSED) {
        if(btn1) {
            lv_obj_set_style_bg_opa(btn1, LV_OPA_40, 0);
        }
    } else if(code == LV_EVENT_RELEASED || code == LV_EVENT_DEFOCUSED) {
        if(btn1) {
            lv_obj_set_style_bg_opa(btn1, LV_OPA_20, 0);
        }
    }
}

// 按钮2 点击事件回调函数（买票）

void button2_click_handler(lv_event_t * e)
{
    safe_event_handler(e);
    if(!e) return;

    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        LV_LOG_USER("Handling ticket purchase click");
        // 停止定时器
        if(slide_timer) {
            lv_timer_pause(slide_timer);
        }
        // 隐藏当前界面
        if(slideshow_screen) {
            lv_obj_add_flag(slideshow_screen, LV_OBJ_FLAG_HIDDEN);
            slideshow_screen_hidden = true;
        }
        // 跳转到购票页面
        buy_tickets_screen_init();
    }
    
    // 添加按钮按下效果
    else if(code == LV_EVENT_PRESSED) {
        if(btn2) {
            lv_obj_set_style_bg_opa(btn2, LV_OPA_40, 0);
        }
    } else if(code == LV_EVENT_RELEASED || code == LV_EVENT_DEFOCUSED) {
        if(btn2) {
            lv_obj_set_style_bg_opa(btn2, LV_OPA_20, 0);
        }
    }
}

// 按钮3 点击事件回调函数（返回）

void button3_click_handler(lv_event_t * e)
{
    safe_event_handler(e);
    if(!e) return;

    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        LV_LOG_USER("Handling back click");
        // 隐藏当前界面而不是删除
        if(slideshow_screen) {
            lv_obj_add_flag(slideshow_screen, LV_OBJ_FLAG_HIDDEN);
            slideshow_screen_hidden = true;
        }
        
        // 跳转到首页面
        first_screen_init();
    }
    else if(code == LV_EVENT_PRESSED) {
        if(btn3) {
            lv_obj_set_style_bg_opa(btn3, LV_OPA_40, 0);
        }
    } else if(code == LV_EVENT_RELEASED || code == LV_EVENT_DEFOCUSED) {
        if(btn3) {
            lv_obj_set_style_bg_opa(btn3, LV_OPA_20, 0);
        }
    }
}

// 创建通用按钮
static lv_obj_t * create_button(lv_obj_t * parent, const char * text, lv_coord_t x, lv_coord_t y, lv_coord_t w,
                                lv_coord_t h, lv_event_cb_t event_cb)
{
    if (!parent || !text || !event_cb) return NULL;
    
    lv_obj_t * btn = lv_btn_create(parent);
    if (!btn) return NULL;
    
    lv_obj_set_size(btn, w, h);
    lv_obj_align(btn, LV_ALIGN_CENTER, x, y);
    lv_obj_set_style_bg_color(btn, lv_color_hex(0xffffff), 0);
    lv_obj_set_style_bg_opa(btn, LV_OPA_20, 0);
    lv_obj_set_style_radius(btn, 8, 0); // 圆角
    lv_obj_set_style_border_width(btn, 1, 0);
    lv_obj_set_style_border_color(btn, lv_color_hex(0xffffff), 0);
    lv_obj_clear_flag(btn, LV_OBJ_FLAG_SCROLLABLE);

    lv_obj_t * label = lv_label_create(btn);
    if (label) {
        lv_obj_set_style_text_font(label, &SourceHanSansCN_Light_2_16_all, LV_PART_MAIN);
        lv_label_set_text(label, text);
        lv_obj_center(label);
        lv_obj_set_style_text_color(label, lv_color_hex(0xffffff), LV_PART_MAIN);
    }

    lv_obj_add_event_cb(btn, event_cb, LV_EVENT_ALL, NULL);
    lv_obj_add_flag(btn, LV_OBJ_FLAG_CLICKABLE);

    return btn;
}

void create_image_slideshow(void)
{
    LV_LOG_USER("Creating image slideshow");

    // 如果幻灯片屏幕已存在，直接显示它并重启定时器
    if(slideshow_screen) {
        LV_LOG_USER("Slideshow screen already exists");
        if(slideshow_screen_hidden) {
            lv_obj_clear_flag(slideshow_screen, LV_OBJ_FLAG_HIDDEN);
            slideshow_screen_hidden = false;
        }
        lv_scr_load_anim(slideshow_screen, LV_SCR_LOAD_ANIM_FADE_ON, 300, 0, false);
        if(slide_timer) {
            lv_timer_resume(slide_timer);
        } else {
            // 如果定时器为NULL，重新创建它
            slide_timer = lv_timer_create(img_switch_timer, 5000, NULL);
        }
        return;
    }

    // 动态加载图片路径
    load_images_from_directory();

    // 1. 创建全屏背景
    slideshow_screen = lv_obj_create(NULL);
    if(!slideshow_screen) {
        LV_LOG_USER("Failed to create slideshow screen object");
        return;
    }

    LV_LOG_USER("Created slideshow screen: %p", slideshow_screen);
    lv_obj_set_size(slideshow_screen, 800, 480);
    lv_obj_set_style_bg_color(slideshow_screen, lv_color_hex(0x000000), 0); // 黑色背景
    lv_obj_clear_flag(slideshow_screen, LV_OBJ_FLAG_SCROLLABLE);

    // 创建图片对象
    img = lv_img_create(slideshow_screen);
    if(!img) {
        LV_LOG_USER("Failed to create image object");
        return;
    }
    lv_obj_align(img, LV_ALIGN_CENTER, 0, 0);

    // 加载第一张图片并处理可能的错误
    if (img_count > 0) {
        lv_img_header_t header;
        lv_res_t result = lv_img_decoder_get_info(img_path[0], &header);
        if(result == LV_RES_OK) {
            set_image_adaptive(img, img_path[0], 800, 480);
        } else {
            // 图片加载失败时显示提示
            lv_obj_set_size(img, 800, 480);
            lv_obj_set_style_bg_color(img, lv_color_hex(0x333333), 0);

            lv_obj_t * err_label = lv_label_create(img);
            if(err_label) {
                lv_label_set_text(err_label, "图片加载失败");
                lv_obj_set_style_text_color(err_label, lv_color_hex(0xff0000), LV_PART_MAIN);
                lv_obj_center(err_label);
            }
        }
    }

    // 创建顶部信息栏
    lv_obj_t * top_bar = lv_obj_create(slideshow_screen);
    if(!top_bar) {
        LV_LOG_USER("Failed to create top bar");
        return;
    }
    lv_obj_set_size(top_bar, 800, 40);
    lv_obj_align(top_bar, LV_ALIGN_TOP_LEFT, 0, 0);
    lv_obj_set_style_bg_color(top_bar, lv_color_hex(0x000000), 0);
    lv_obj_set_style_bg_opa(top_bar, LV_OPA_100, 0);    // 纯黑色
    lv_obj_clear_flag(top_bar, LV_OBJ_FLAG_SCROLLABLE); // 禁止滚动

    // 创建影院标题
    lv_obj_t * label_cinema = lv_label_create(top_bar);
    if(label_cinema) {
        lv_obj_set_style_text_font(label_cinema, &SourceHanSansCN_Light_2_16_all, LV_PART_MAIN);
        lv_label_set_text(label_cinema, "栗子电影院");
        lv_obj_align(label_cinema, LV_ALIGN_LEFT_MID, 20, 0);
        lv_obj_set_style_text_color(label_cinema, lv_color_hex(0xffffff), LV_PART_MAIN);
    }

    // 创建时间标签
    label_time = lv_label_create(top_bar);
    if(label_time) {
        lv_obj_set_style_text_font(label_time, &SourceHanSansCN_Light_2_16_all, LV_PART_MAIN);
        lv_label_set_text(label_time, "加载中...");
        lv_obj_align(label_time, LV_ALIGN_RIGHT_MID, -20, 0);
        lv_obj_set_style_text_color(label_time, lv_color_hex(0xffffff), LV_PART_MAIN);
    }

    // 启动时间更新定时器
    if(!time_timer) {
        time_timer = lv_timer_create(update_time_timer, 1000, NULL);
    }

    // 创建功能按钮
    btn1 = create_button(slideshow_screen, "取票", -120, 150, 100, 50, button1_click_handler);
    btn2 = create_button(slideshow_screen, "买票", 120, 150, 100, 50, button2_click_handler);
    btn3 = create_button(slideshow_screen, "返回", 320, 200, 80, 40, button3_click_handler);

    // 加载画布到屏幕（使用动画效果）
    lv_scr_load_anim(slideshow_screen, LV_SCR_LOAD_ANIM_FADE_ON, 300, 0, false);

    // 创建并启动幻灯片定时器
    if(!slide_timer) {
        slide_timer = lv_timer_create(img_switch_timer, 5000, NULL);
    } else {
        lv_timer_reset(slide_timer);
        lv_timer_resume(slide_timer);
    }

    LV_LOG_USER("Finished creating slideshow");
}